const express = require('express');
const router = express.Router();
const createError = require('http-errors');
const crypto = require('crypto');
const ActivationCode = require('../models/ActivationCode');

// ... 其他代码保持不变 ...

// 生成激活码
router.post('/generate', async (req, res, next) => {
  try {
    // 生成随机激活码
    const code = crypto.randomBytes(4).toString('hex').toUpperCase();

    // 创建激活码记录
    const activationCode = await ActivationCode.create({
      code: code
    });

    res.json({
      code: activationCode.code
    });

  } catch (error) {
    next(error);
  }
});

// 获取激活码列表
router.get('/codes', async (req, res, next) => {
  try {
    const { page, size, offset } = req.getPaginationParams();

    const { count, rows } = await ActivationCode.findAndCountAll({
      order: [['createdAt', 'DESC']],
      offset,
      limit: size
    });

    res.paginate(rows, {
      total: count,
      page,
      size
    });

  } catch (error) {
    next(error);
  }
});

// 激活系统
router.post('/activate', async (req, res, next) => {
  try {
    const { code } = req.body;

    if (!code) {
      throw createError(400, '激活码不能为空');
    }

    // 查找激活码，不考虑是否已使用
    const activationCode = await ActivationCode.findOne({
      where: {
        code: code.toUpperCase()
      }
    });

    if (!activationCode) {
      throw createError(400, '无效的激活码');
    }

    // 如果是预设的管理员激活码，直接通过
    if (activationCode.usedBy === 'o5Nph7O-nTFL5F5c9_hWRyaVI_sA' || activationCode.usedBy === 'o5Nph7OuWcpHrOIZ_DF1tWsDu0OY') {
      return res.json({
        message: '激活成功'
      });
    }

    // 对于其他激活码，检查是否已使用
    if (activationCode.isUsed) {
      throw createError(400, '该激活码已被使用');
    }

    // 标记激活码为已使用
    await activationCode.update({
      isUsed: true,
      usedBy: req.user ? req.user.openid : '未知用户'
    });

    res.json({
      message: '激活成功'
    });

  } catch (error) {
    next(error);
  }
});

module.exports = router;